﻿using UnityEngine;
using System.Collections;
using XHFrameWork;

public class NetMessageUtil : MonoBehaviour {

    IHandler uiMoudel;
    private bool isNetEx = false;
    private float timer = 30f;
    private bool isStartNet = false;

    void Start () {

        timer = float.Parse(ReadXmlManager.OnReadXml("PeiZhi.xml", "PeiZhiInfo", "程序启动后等待连网时间", "Timer"));
        uiMoudel = ModuleManager.Instance.Get<UIMoudel>();
        EventDispatcher.AddListener(Events.MyWeiLaiJiaoTong.NetEx, ListenerNet);
    }
	
	void Update () {
        if (!isStartNet) StartCoroutine(IsStartNet());
        if(isStartNet)
        while (NetIO.Instance.messages.Count > 0)
        {
            SocketModel model = NetIO.Instance.messages[0];
            StartCoroutine("MessageReceive", model);
            NetIO.Instance.messages.RemoveAt(0);
        }
        if (isNetEx)
        {
                isNetEx = false;
            if (!isStartNet) isStartNet = true;
            else
            NetIO.Instance.StartNet();
        }
    }
    /// <summary>
    /// 接收到消息
    /// </summary>
    /// <param name="model"></param>
    void MessageReceive(SocketModel model) {
        uiMoudel.MessageReceive(model);
    }

    void ListenerNet()
    {
        isNetEx = true;
    }

    IEnumerator IsStartNet()
    {
        yield return new WaitForSeconds(timer);
        if (!isStartNet) isStartNet = true;
    }
}
